package com.efounder.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Build;
import androidx.annotation.IntDef;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.efounder.mobilemanager.R;
import com.efounder.utils.JfResourceUtil;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.UUID;

/**
 * Created by Marcello on 2019/11/12
 * 通用titlebar 的基类,中间布局在子类实现
 */
public abstract class BaseTitleBar extends RelativeLayout implements View.OnClickListener {
    private StatusPlaceholderView viewStatusBarFill;                     // 状态栏填充视图
    protected RelativeLayout rlMain;                      // 主视图

    protected TextView tvLeft;                            // 左边TextView
    protected ImageView imgLeft;                        // 左边ImageView
    protected View viewCustomLeft;
    protected TextView tvRight;                           // 右边TextView
    protected ImageView imgRight;                       // 左边ImageView
    protected View viewCustomRight;

    protected int titleBarDrawable;                          // 标题栏背景颜
    protected int titleBarHeight;                         // 标题栏高度

    protected int leftType;                               // 左边视图类型
    protected String leftText;                            // 左边TextView文字
    protected int leftTextColor=R.color.comm_titlebar_text_selector;                          // 左边TextView颜色
    protected float leftTextSize=dpToPx(14f);                         // 左边TextView文字大小
    protected int leftDrawable;                           // 左边TextView drawableLeft资源
    protected float leftDrawablePadding=dpToPx(5f);                  // 左边TextView drawablePadding
    protected int leftImageResource;                      // 左边图片资源
    protected int leftImageStyle;                      // 左边图片资源的style
    protected int leftCustomViewRes;                      // 左边自定义视图布局资源

    protected int rightType;                              // 右边视图类型
    protected String rightText;                           // 右边TextView文字
    protected int rightTextColor=R.color.comm_titlebar_text_selector;                         // 右边TextView颜色
    protected float rightTextSize=dpToPx(14f);                        // 右边TextView文字大小
    protected int rightImageResource;                     // 右边图片资源
    protected int rightCustomViewRes;                     // 右边自定义视图布局资源



    protected CommonTitleBar.OnTitleBarListener titleBarListener;

    public static final int TYPE_LEFT_NONE = 0;
    public static final int TYPE_LEFT_TEXTVIEW = 1;
    public static final int TYPE_LEFT_IMAGEVIEW = 2;
    public static final int TYPE_LEFT_CUSTOM_VIEW = 3;
    public static final int TYPE_LEFT_IMAGEVIEW_BACK = 4;
    public static final int TYPE_LEFT_IMAGEVIEW_CLOSE = 5;
    public static final int TYPE_RIGHT_NONE = 0;
    public static final int TYPE_RIGHT_TEXTVIEW = 1;
    public static final int TYPE_RIGHT_IMAGEVIEW = 2;
    public static final int TYPE_RIGHT_CUSTOM_VIEW = 3;

    private int PADDING_5;
    private int PADDING_8;
    protected int PADDING_50;

    @IntDef({TYPE_LEFT_NONE, TYPE_LEFT_TEXTVIEW, TYPE_LEFT_IMAGEVIEW, TYPE_LEFT_CUSTOM_VIEW,TYPE_LEFT_IMAGEVIEW_BACK,TYPE_LEFT_IMAGEVIEW_CLOSE})
    @Retention(RetentionPolicy.SOURCE)
    public @interface LeftTypeDef {
    }
    @IntDef({TYPE_RIGHT_NONE, TYPE_RIGHT_TEXTVIEW, TYPE_RIGHT_IMAGEVIEW, TYPE_RIGHT_CUSTOM_VIEW})
    @Retention(RetentionPolicy.SOURCE)
    public @interface RightTypeDef {
    }

    public BaseTitleBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        loadAttributes(context, attrs);
        initGlobalViews(context);
        initMainViews(context);
    }

    private void loadAttributes(Context context, AttributeSet attrs) {
        PADDING_5 = dpToPx(5);
        PADDING_8 = dpToPx(8);
        PADDING_50 = dpToPx(50);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.CommonTitleBar);
        titleBarDrawable = array.getResourceId(R.styleable.CommonTitleBar_titleBarDrawable, R.drawable.common_title_background_drawable);
        titleBarHeight = (int) array.getDimension(R.styleable.CommonTitleBar_titleBarHeight, dpToPx(48f));

        //左边的布局
        leftType = array.getInt(R.styleable.CommonTitleBar_leftType, TYPE_LEFT_IMAGEVIEW_BACK);
        if (leftType == TYPE_LEFT_TEXTVIEW) {
            leftText = array.getString(R.styleable.CommonTitleBar_leftText);
            leftTextColor = array.getResourceId(R.styleable.CommonTitleBar_leftTextColor, R.color.comm_titlebar_text_selector);
            leftTextSize = array.getDimension(R.styleable.CommonTitleBar_leftTextSize, dpToPx(14f));
            leftDrawable = array.getResourceId(R.styleable.CommonTitleBar_leftDrawable, 0);
            leftDrawablePadding = array.getDimension(R.styleable.CommonTitleBar_leftDrawablePadding, 5);
        } else if (leftType == TYPE_LEFT_IMAGEVIEW) {
            leftImageResource = array.getResourceId(R.styleable.CommonTitleBar_leftImageResource, R.drawable.ef_title_view_back_normal);
        } else if (leftType == TYPE_LEFT_CUSTOM_VIEW) {
            leftCustomViewRes = array.getResourceId(R.styleable.CommonTitleBar_leftCustomView, 0);
        } else if (leftType == TYPE_LEFT_IMAGEVIEW_BACK) {
            leftImageResource = array.getResourceId(R.styleable.CommonTitleBar_leftImageResource, R.drawable.ef_title_view_back_normal);
            leftImageStyle = array.getResourceId(R.styleable.CommonTitleBar_leftImageStyle, R.style.style_back_image_button);
        } else if (leftType == TYPE_LEFT_IMAGEVIEW_CLOSE) {
            leftImageResource = array.getResourceId(R.styleable.CommonTitleBar_leftImageResource, R.drawable.iv_close);
            leftImageStyle = array.getResourceId(R.styleable.CommonTitleBar_leftImageStyle, R.style.style_left_close_image_button);
        }
        //右边的布局
        rightType = array.getInt(R.styleable.CommonTitleBar_rightType, TYPE_RIGHT_NONE);
        if (rightType == TYPE_RIGHT_TEXTVIEW) {
            rightText = array.getString(R.styleable.CommonTitleBar_rightText);
            rightTextColor = array.getResourceId(R.styleable.CommonTitleBar_rightTextColor, R.color.comm_titlebar_text_selector);
            rightTextSize = array.getDimension(R.styleable.CommonTitleBar_rightTextSize, dpToPx(14f));
        } else if (rightType == TYPE_RIGHT_IMAGEVIEW) {
            rightImageResource = array.getResourceId(R.styleable.CommonTitleBar_rightImageResource, 0);
        } else if (rightType == TYPE_RIGHT_CUSTOM_VIEW) {
            rightCustomViewRes = array.getResourceId(R.styleable.CommonTitleBar_rightCustomView, 0);
        }
        loadAttributesCenterView(array);

        array.recycle();
    }

    //根据子类不同需求实现中间的布局
    protected abstract void loadAttributesCenterView(TypedArray array);

    protected final int MATCH_PARENT = ViewGroup.LayoutParams.MATCH_PARENT;
    protected final int WRAP_CONTENT = ViewGroup.LayoutParams.WRAP_CONTENT;

    /**
     * 初始化全局视图
     *
     * @param context 上下文
     */
    private void initGlobalViews(Context context) {
        ViewGroup.LayoutParams globalParams = new ViewGroup.LayoutParams(MATCH_PARENT, WRAP_CONTENT);
        setLayoutParams(globalParams);

        // 构建标题栏填充视图,设置统一的背景
        viewStatusBarFill = new StatusPlaceholderView(context);
        viewStatusBarFill.setId(R.id.status_bar_view);
        addView(viewStatusBarFill);

        // 构建主视图
        rlMain = new RelativeLayout(context);
        RelativeLayout.LayoutParams mainParams = new RelativeLayout.LayoutParams(MATCH_PARENT, titleBarHeight);
        mainParams.addRule(RelativeLayout.BELOW, viewStatusBarFill.getId());


        addView(rlMain, mainParams);
        setBackground(JfResourceUtil.getSkinDrawable(titleBarDrawable));

    }

    /**
     * 初始化主视图
     *
     * @param context 上下文
     */
    private void initMainViews(Context context) {
        if (leftType != TYPE_LEFT_NONE) {
            initMainLeftViews(context);
        }
        if (rightType != TYPE_RIGHT_NONE) {
            initMainRightViews(context);
        }
            initMainCenterViews(context);
    }

    /**
     * 初始化主视图左边部分
     * -- add: adaptive RTL
     *
     * @param context 上下文
     */
    private void initMainLeftViews(Context context) {
        RelativeLayout.LayoutParams leftInnerParams = new RelativeLayout.LayoutParams(WRAP_CONTENT, MATCH_PARENT);
        leftInnerParams.addRule(RelativeLayout.ALIGN_PARENT_START);
        leftInnerParams.addRule(RelativeLayout.CENTER_VERTICAL);

        if (leftType == TYPE_LEFT_TEXTVIEW) {
            // 初始化左边TextView
            tvLeft = new TextView(context);
            tvLeft.setText(leftText);
            tvLeft.setId(generateViewId());
            tvLeft.setTextColor(JfResourceUtil.getSkinColor(leftTextColor));
            tvLeft.setTextSize(TypedValue.COMPLEX_UNIT_PX, leftTextSize);
            tvLeft.setGravity(Gravity.START | Gravity.CENTER_VERTICAL);
            tvLeft.setSingleLine(true);
            tvLeft.setOnClickListener(this);
            // 设置DrawableLeft及DrawablePadding
            if (leftDrawable != 0) {
                tvLeft.setCompoundDrawablePadding((int) leftDrawablePadding);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    tvLeft.setCompoundDrawablesRelativeWithIntrinsicBounds(leftDrawable, 0, 0, 0);
                } else {
                    tvLeft.setCompoundDrawablesWithIntrinsicBounds(leftDrawable, 0, 0, 0);
                }
            }
            tvLeft.setPadding(PADDING_8, 0, 0, 0);

            rlMain.addView(tvLeft, leftInnerParams);

        } else if (leftType == TYPE_LEFT_IMAGEVIEW) {
            addLeftImageView(context, leftInnerParams);

        } else if (leftType == TYPE_LEFT_CUSTOM_VIEW) {
            // 初始化自定义View
            viewCustomLeft = LayoutInflater.from(context).inflate(leftCustomViewRes, rlMain, false);
            LayoutParams layoutParams = (LayoutParams) viewCustomLeft.getLayoutParams();
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_START);
            layoutParams.addRule(RelativeLayout.CENTER_VERTICAL);
            if (viewCustomLeft.getId() == View.NO_ID) {
                viewCustomLeft.setId(generateViewId());
            }
            rlMain.addView(viewCustomLeft);
        } else if (leftType == TYPE_LEFT_IMAGEVIEW_BACK) {
            leftInnerParams.height = dpToPx(48f);
            leftInnerParams.width = dpToPx(45f);
            addLeftImageView(context, leftInnerParams);

        } else if (leftType == TYPE_LEFT_IMAGEVIEW_CLOSE) {
            leftInnerParams.height = dpToPx(26f);
            leftInnerParams.width = dpToPx(26f);
            addLeftImageView(context, leftInnerParams);
        }
    }

    private void addLeftImageView(Context context, RelativeLayout.LayoutParams leftInnerParams) {
        // 初始化左边ImageView
        if (leftImageStyle != 0) {
            ContextThemeWrapper contextThemeWrapper = new ContextThemeWrapper(context, leftImageStyle);
            imgLeft = new ImageView(contextThemeWrapper, null, 0);
        } else {
            imgLeft = new ImageView(context);
        }
        imgLeft.setImageResource(leftImageResource);
        imgLeft.setId(generateViewId());
        imgLeft.setOnClickListener(this);
        rlMain.addView(imgLeft, leftInnerParams);
    }

    /**
     * 初始化主视图右边部分
     *
     * @param context 上下文
     */
    private void initMainRightViews(Context context) {
        RelativeLayout.LayoutParams rightInnerParams = new RelativeLayout.LayoutParams(WRAP_CONTENT, dpToPx(32f));
        rightInnerParams.addRule(RelativeLayout.ALIGN_PARENT_END);
        rightInnerParams.addRule(RelativeLayout.CENTER_VERTICAL);

        if (rightType == TYPE_RIGHT_TEXTVIEW) {
            // 初始化右边TextView
            tvRight = new TextView(context);
            tvRight.setId(generateViewId());
            tvRight.setText(rightText);
            tvRight.setTextColor(JfResourceUtil.getSkinColor(rightTextColor));
            tvRight.setTextSize(TypedValue.COMPLEX_UNIT_PX, rightTextSize);
            tvRight.setGravity(Gravity.CENTER);
            tvRight.setSingleLine(true);
            tvRight.setMinWidth(dpToPx(48f));
            tvRight.setMinimumWidth(dpToPx(48f));
            tvRight.setMaxWidth(dpToPx(60f));
            tvRight.setOnClickListener(this);
            rightInnerParams.setMargins(0,0,PADDING_8,0);
            rlMain.addView(tvRight, rightInnerParams);

        } else if (rightType == TYPE_RIGHT_IMAGEVIEW) {
            // 初始化右边ImageView
            rightInnerParams = new RelativeLayout.LayoutParams(dpToPx(40f), dpToPx(40f));
            rightInnerParams.addRule(RelativeLayout.ALIGN_PARENT_END);
            rightInnerParams.addRule(RelativeLayout.CENTER_VERTICAL);
            rightInnerParams.setMargins(0, 0, PADDING_5, 0);
            imgRight = new ImageView(context);
            imgRight.setId(generateViewId());
            imgRight.setImageResource(rightImageResource);
            imgRight.setBackgroundColor(Color.TRANSPARENT);
            imgRight.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imgRight.setOnClickListener(this);
            rlMain.addView(imgRight, rightInnerParams);

        } else if (rightType == TYPE_RIGHT_CUSTOM_VIEW) {
            // 初始化自定义view
            viewCustomRight = LayoutInflater.from(context).inflate(rightCustomViewRes, rlMain, false);
            LayoutParams layoutParams = (LayoutParams) viewCustomRight.getLayoutParams();
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_START);
            layoutParams.addRule(RelativeLayout.CENTER_VERTICAL);
            if (viewCustomRight.getId() == View.NO_ID) {
                viewCustomRight.setId(generateViewId());
            }
            rlMain.addView(viewCustomRight);
        }
    }

    /**
     * 根据子类的需要初始化主视图中间部分,具体实现在子类
     *
     * @param context 上下文
     */
    protected abstract void initMainCenterViews(Context context);


    @Override
    public void onClick(View v) {
        if (titleBarListener == null) return;
        if (v.equals(tvLeft)) {
            titleBarListener.onClicked(v, ACTION_LEFT_TEXT);
        } else if (v.equals(imgLeft)) {
            titleBarListener.onClicked(v, ACTION_LEFT_IMAGEVIEW);
        } else if (v.equals(tvRight)) {
            titleBarListener.onClicked(v, ACTION_RIGHT_TEXT);
        } else if (v.equals(imgRight)) {
            titleBarListener.onClicked(v, ACTION_RIGHT_IMAGEVIEW);
        }
    }


    /**
     * 设置状态栏颜色
     *
     * @param color
     */
    public void setStatusBarColor(int color) {
        if (viewStatusBarFill != null) {
            viewStatusBarFill.setBackgroundColor(color);
        }
    }


    /**
     * 获取标题栏左边TextView，对应leftType = textView
     *
     * @return
     */
    public TextView getLeftTextView() {
        return tvLeft;
    }

    /**
     * 获取标题栏左边ImageView，对应leftType = ImageView
     *
     * @return
     */
    public ImageView getLeftImageView() {
        return imgLeft;
    }

    /**
     * 获取标题栏右边TextView，对应rightType = textView
     *
     * @return
     */
    public TextView getRightTextView() {
        return tvRight;
    }

    /**
     * 获取标题栏右边ImageView，对应rightType = ImageView
     *
     * @return
     */
    public ImageView getRightImageView() {
        return imgRight;
    }



    /**
     * 获取左边自定义布局
     *
     * @return
     */
    public View getLeftCustomView() {
        return viewCustomLeft;
    }

    /**
     * 获取右边自定义布局
     *
     * @return
     */
    public View getRightCustomView() {
        return viewCustomRight;
    }


    /**
     * @param leftView
     */
    public void setLeftView(View leftView) {
        if (leftView.getId() == View.NO_ID) {
            leftView.setId(generateViewId());
        }
       LayoutParams layoutParams = (LayoutParams) leftView.getLayoutParams();
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_START);
        layoutParams.addRule(RelativeLayout.CENTER_VERTICAL);
        rlMain.addView(leftView);
    }


    /**
     * @param rightView
     */
    public void setRightView(View rightView) {
        if (rightView.getId() == View.NO_ID) {
            rightView.setId(generateViewId());
        }
        LayoutParams layoutParams = (LayoutParams) rightView.getLayoutParams();
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_START);
        layoutParams.addRule(RelativeLayout.CENTER_VERTICAL);
        rlMain.addView(rightView);
    }

    /**
     * @param leftType
     */
    public BaseTitleBar setLeftType(@LeftTypeDef int leftType) {
        this.leftType = leftType;
        clearLeftViews();
        initMainLeftViews(getContext());
        return this;
    }

    /**
     * @param imageResource 设置左边的图片资源
     */
    public BaseTitleBar setLeftImageResource(int imageResource) {
        this.leftType = TYPE_LEFT_IMAGEVIEW;
        this.leftImageResource = imageResource;
        if (imgLeft != null) {
            imgLeft.setImageResource(imageResource);
        } else {
            clearLeftViews();
            initMainLeftViews(getContext());
        }
        return this;
    }

    /**
     * @param leftImageStyle leftType==TYPE_LEFT_IMAGEVIEW
     */
    public BaseTitleBar setLeftImageViewStyle(int leftImageStyle) {
        this.leftType = TYPE_LEFT_IMAGEVIEW;
        this.leftImageStyle = leftImageStyle;
        clearLeftViews();
        initMainLeftViews(getContext());
        return this;
    }

    /**
     * 设置左边返回类型按钮
     */
    public BaseTitleBar setLeftBcakImageView() {
        this.leftType = TYPE_LEFT_IMAGEVIEW_BACK;
        clearLeftViews();
        RelativeLayout.LayoutParams leftInnerParams = new RelativeLayout.LayoutParams(dpToPx(45f), dpToPx(48f));
        leftInnerParams.addRule(RelativeLayout.ALIGN_PARENT_START);
        leftInnerParams.addRule(RelativeLayout.CENTER_VERTICAL);
        addLeftImageView(getContext(), leftInnerParams);
        return this;
    }

    /**
     * 设置左边返回类型按钮
     */
    public BaseTitleBar setLeftCloseImageView() {
        this.leftType = TYPE_LEFT_IMAGEVIEW_CLOSE;
        clearLeftViews();
        RelativeLayout.LayoutParams leftInnerParams = new RelativeLayout.LayoutParams(dpToPx(26f), dpToPx(26f));
        leftInnerParams.addRule(RelativeLayout.ALIGN_PARENT_START);
        leftInnerParams.addRule(RelativeLayout.CENTER_VERTICAL);
        addLeftImageView(getContext(), leftInnerParams);
        return this;
    }

    /**
     * @param rightType
     */
    public BaseTitleBar setRightType(@RightTypeDef int rightType) {
        this.rightType = rightType;
        clearRightViews();
        initMainRightViews(getContext());
        return this;
    }

    /**
     * @param imageResource 设置右侧布局的imageResource
     */
    public BaseTitleBar setRightImageResource(int imageResource) {
        this.rightType = TYPE_RIGHT_IMAGEVIEW;
        this.rightImageResource = imageResource;
        if (imgRight != null) {
            imgRight.setImageResource(imageResource);
        } else {
            clearRightViews();
            initMainRightViews(getContext());
        }

        return this;
    }

    /**
     * @param rightText 设置右侧布局的text
     */
    public BaseTitleBar setRightText(String rightText) {
        this.rightType = TYPE_RIGHT_TEXTVIEW;
        this.rightText = rightText;
        if (tvRight != null) {
            tvRight.setText(rightText);
        } else {
            clearRightViews();
            initMainRightViews(getContext());
        }
        return this;
    }



    //remove 右侧多余的views
    private void clearRightViews() {
        if (tvRight != null) {
            rlMain.removeView(tvRight);
        } else if (imgRight != null) {
            rlMain.removeView(imgRight);
        } else if (viewCustomRight != null) {
            rlMain.removeView(viewCustomRight);
        }
    }

    //remove 左侧侧多余的views
    private void clearLeftViews() {
        if (tvLeft != null) {
            rlMain.removeView(tvLeft);
        } else if (imgLeft != null) {
            rlMain.removeView(imgLeft);
        } else if (viewCustomLeft != null) {
            rlMain.removeView(viewCustomLeft);
        }
    }

    /**
     * 设置点击事件监听
     *
     * @param listener
     */

    public void setOnTitleBarListener(CommonTitleBar.OnTitleBarListener listener) {
        this.titleBarListener = listener;
    }


    public static final int ACTION_LEFT_TEXT = 1;        // 左边TextView被点击
    public static final int ACTION_LEFT_IMAGEVIEW = 2;      // 左边ImageView被点击
    public static final int ACTION_RIGHT_TEXT = 3;       // 右边TextView被点击
    public static final int ACTION_RIGHT_IMAGEVIEW = 4;     // 右边ImageView被点击


    /**
     * 点击事件
     */
    public interface OnTitleBarListener {
        /**
         * @param v
         * @param action 对应ACTION_XXX, 如ACTION_LEFT_TEXT
         */
        void onClicked(View v, int action);
    }

    /**
     * 计算View Id
     *
     * @return
     */
    public static int generateViewId() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            return View.generateViewId();
        } else {
            return UUID.randomUUID().hashCode();
        }
    }

    protected int dpToPx(float dp) {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, dm);
    }
}
